package day03pm;

import jdk.net.Sockets;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 服务器端改造
 * @author JokerQ
 * @date 2020/8/25 - 13:03
 */
public class Server_v6 {
    private ServerSocket serverSocket;
    //set集合存储所有客户端发来的消息
    private Set<Socket> sockets;

    public Server_v6() throws Exception {
        System.out.println("服务端启动！！！");
        serverSocket = new ServerSocket(8888);
        //实例化
        sockets = new HashSet<Socket>();
    }
    public void init() throws Exception {
        while (true){
            Socket socket = serverSocket.accept();
            //把所有的客户端socket都加入到set集合中
            sockets.add(socket);
            new ServerThread(socket).start();
            System.out.println("一个客户端连接了...");
        }

    }
    class ServerThread extends Thread{
        private Socket socket;
        private BufferedReader reader;
        public ServerThread(Socket socket) throws Exception {
            this.socket=socket;
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            reader = new BufferedReader(isr);
        }

        @Override
        public void run() {
            while (true){
                String str = null;
                try {
                    str = reader.readLine();
                    System.out.println("收到客户端发来："+str);
                    sendMsgToAllClient(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        /**
         * 发送给所有客户端
         * @param msg
         * @throws Exception
         */
        public void sendMsgToAllClient(String msg) throws Exception {
            //遍历set集合
            for(Socket s : sockets){
                OutputStream out = s.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"utf-8"),true);
                writer.println(msg+"\t["+
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"]");
                writer.flush();
            }
        }
    }
    public static void main(String[] args) throws Exception {
        Server_v6 server = new Server_v6();
        server.init();
    }

}

